<template>
  <div class="app">
    <el-card style="width: 480px">
      <template #header>
        <div class="card-header">
          <h1>Card name</h1>
        </div>
      </template>
      <!-- 登陆表单 -->
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item label="用户名" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)"> 登录 </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>

      <template #footer>管理系统</template>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { loginRequest } from '@/api/user'
import router from '@/router'
import { ElMessage } from 'element-plus'

//接口--RulerForm 控制表单中有哪些属性
interface RuleForm {
  name: string
  password: string
}

const formSize = ref<ComponentSize>('default')

//组件实例
//ref<泛型-类型>（）  限制的是函数的参数或返回值的类型
const ruleFormRef = ref<FormInstance>()

//响应式数据
// reactive<类型> 这个类型，展示reactive参数的类型，必须按照上面的接口定义（接口里有什么这里就写什么）
const ruleForm = reactive<RuleForm>({
  name: 'admin',
  password: '',
})

//表单的校验规则
//FormRules限制是的验证规则可以有哪些属性（同样，上面有什么参数，这里就写什么参数）
const rules = reactive<FormRules<RuleForm>>({
  password: [
    {
      pattern: /^.{5,}$/,
      message: '密码至少五位非空字符串',
      required: true,
    },
  ],
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 35, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
})

interface IRegData {
  code: string
  message: string
  data: {
    token: string
    adminname: string
  }
}

// formEl-form表单的组件实例
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  //validate对整个表单的内容进行验证。接收一个回调函数，或返回Promise 。
  await formEl.validate(async (valid, fields) => {
    //valid是否校验通过

    if (valid) {
      console.log('submit!')
      //校验通过-》调用登录接口--》登录成功进行跳转
      const r = await loginRequest(ruleForm.name, ruleForm.password)
      console.log(r.data)

      let data: IRegData = r.data 
      if (data.code == '200') {
        ElMessage({
          message: data.message,
          type: 'success',
          plain: true,
        })
        localStorage.setItem('admin-token', data.data.token)
        localStorage.setItem('admin-adminname', data.data.adminname)
        router.push('/home')
      } else {
        // fields --校验不通过 规则对象
        ElMessage({
          message: data.message,
          type: 'error',
          plain: true,
        })
      }
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// const options = Array.from({ length: 10000 }).map((_, idx) => ({
//   value: `${idx + 1}`,
//   label: `${idx + 1}`,
// }))
</script>
<style scoped lang="scss">
.app {
  background-image: url('../assets/images/bg.jpg');
  height: 100%;
  display: flex;
  .el-card {
    margin: auto;
  }
}
</style>
